package com.example.common.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author 王鹤蒲
 * @Date 2023 08 23
 */
@Component
public class RedisUtil {

    private static RedisUtil redisUtil;

    @Resource
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init(){
        redisUtil=this;
        redisUtil.redisTemplate=this.redisTemplate;
    }

    public static boolean expire(String key, long time) {
        return redisUtil.redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public static long getExpire(String key) {
        return redisUtil.redisTemplate.getExpire(key);
    }

    public static boolean hasKey(String key) {
        return redisUtil.redisTemplate.hasKey(key);
    }

    public static boolean persist(String key) {
        return redisUtil.redisTemplate.boundValueOps(key).persist();
    }

    public static  Object get(String key) {
        return key == null ? null : redisUtil.redisTemplate.boundValueOps(key).get();
    }

    public static void set(String key, String value) {
        redisUtil.redisTemplate.opsForValue().set(key, value);
    }

    public  static void set(String key, String value, long time) {
        if (time > 0) {
            redisUtil.redisTemplate.opsForValue().set(key, value, time);
        } else {
            redisUtil.redisTemplate.opsForValue().set(key, value);
        }
    }


    public  static boolean delete(String key) {
        return  redisUtil.redisTemplate.delete(key);
    }

    public static void multiSet(Map<String, String> map) {
        redisUtil.redisTemplate.opsForValue().multiSet(map);
    }

    public static void multiSetIfAbsent(Map<String, String> map) {
        redisUtil.redisTemplate.opsForValue().multiSetIfAbsent(map);
    }

    public static Long increment(String key, long number) {
        return  redisUtil.redisTemplate.opsForValue().increment(key, number);
    }

    public static Double increment(String key, double number) {
        return  redisUtil.redisTemplate.opsForValue().increment(key, number);
    }

    public static void add(String key, String value) {
        redisUtil.redisTemplate.opsForSet().add(key, value);
    }

    public static Set<Object> members(String key) {
        return  redisUtil.redisTemplate.opsForSet().members(key);
    }

    public static void randomMembers(String key, long count) {
        redisUtil.redisTemplate.opsForSet().randomMembers(key, count);
    }

    public static Object randomMember(String key) {
        return  redisUtil.redisTemplate.opsForSet().randomMember(key);
    }
}
